const express = require('express');
const cors = require('cors');
const http = require('http');
const socketIo = require('socket.io');
const mysql = require('mysql2/promise');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

// 中间件
app.use(cors());
app.use(express.json());

// 数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '@Cl514827', // 请修改为你的MySQL密码
  database: 'sudoku_game'
};

// 创建数据库连接池
const pool = mysql.createPool({
  ...dbConfig,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 路由
app.use('/api/game', require('./routes/game'));
app.use('/api/leaderboard', require('./routes/leaderboard'));
app.use('/api/battle', require('./routes/battle'));

// 健康检查
app.get('/health', (req, res) => {
  res.json({ status: 'OK', message: '数独游戏后端服务运行正常' });
});

// WebSocket处理
io.on('connection', (socket) => {
  console.log('用户连接:', socket.id);
  
  // 加入对战房间
  socket.on('join-battle', (battleId) => {
    socket.join(battleId);
    console.log(`用户 ${socket.id} 加入对战房间 ${battleId}`);
  });
  
  // 处理游戏移动
  socket.on('move', (data) => {
    socket.to(data.battleId).emit('opponent-move', {
      row: data.row,
      col: data.col,
      value: data.value,
      playerId: socket.id
    });
  });
  
  // 游戏完成
  socket.on('game-complete', (data) => {
    socket.to(data.battleId).emit('opponent-complete', {
      playerId: socket.id,
      time: data.time,
      score: data.score
    });
  });
  
  // 断开连接
  socket.on('disconnect', () => {
    console.log('用户断开连接:', socket.id);
  });
});

// 全局错误处理
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: '服务器内部错误' });
});

// 导出数据库连接池供其他模块使用
app.locals.db = pool;

const PORT = process.env.PORT || 3002;
server.listen(PORT, () => {
  console.log(`🚀 数独游戏后端服务器运行在端口 ${PORT}`);
  console.log(`📊 健康检查: http://localhost:${PORT}/health`);
});

module.exports = { app, io, pool };